package com.zprmb.udzt.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.zprmb.udzt.BaseActivity;
import com.zprmb.udzt.BbtApplication;
import com.zprmb.udzt.R;
import com.zprmb.udzt.V6LoginActivity;
import com.zprmb.udzt.util.Constant;
import com.zprmb.udzt.util.KShareViewActivityManager;
import com.zprmb.udzt.util.VolleryUtil;
import com.zprmb.udzt.view.WebViewDialog;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
//import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
//import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
//import com.tencent.smtt.sdk.WebChromeClient;
//import com.tencent.smtt.sdk.WebSettings;
//import com.tencent.smtt.sdk.WebView;
//import com.tencent.smtt.sdk.WebViewClient;


@SuppressLint("SetJavaScriptEnabled")
public class RuleWebActivity extends BaseActivity implements View.OnClickListener {

    private String title;
    private String ref = "";
    private String url;
    private boolean isOnPause = false;

    private WebView v4_webview;


    //	private ProgressBar bar;
    private boolean back = false;
    private WebViewDialog dialog;

    private SharedPreferences sha;
    int flag;
//智投宝Text

    TextView text_zhitou;

    RelativeLayout rl_back;
    ImageView img_back;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rule_webview);
        setImmersionStatus();
        BbtApplication.getInstance().addActvity(this);
        Intent intent = getIntent();
        dialog = new WebViewDialog(this);
        title = intent.getStringExtra("title");
//        url = intent.getStringExtra("url");
//		ref = getShare().getString("usercode", "");
//        Log.e("webview", url);
        // url = "account/invest/8F759CC2-65DB-11E5-AE96-5254002EAABD/contract";
        sha = getSharedPreferences("config", MODE_PRIVATE);

        rl_back = (RelativeLayout) findViewById(R.id.rl_back);
        rl_back.setOnClickListener(this);
        img_back = (ImageView) findViewById(R.id.img_back);
        img_back.setOnClickListener(this);
        initView();
        userinfo2();
        initData();

        flag = getIntent().getIntExtra("flag", 0);
        text_zhitou = (TextView) findViewById(R.id.text_zhitou);
        text_zhitou.setText(getIntent().getStringExtra("content"));
    }

    private void userinfo2() {
        VolleryUtil volleryUtil = new VolleryUtil() {

            @Override
            public void onUpDate(JSONObject jsonObject) {
                Log.d(jsonObject.toString(), "3333333333333333");

                // TODO Auto-generated method stub
                if (jsonObject.optInt("success") == 1) {

                } else {
                    if (jsonObject.optString("comment").equals("please login")) {
//						Editor ed=sha.edit();
//						ed.putInt("islogin", 0);
//						ed.commit();
                        Log.e("login", jsonObject.toString());
                        startActivity(new Intent(RuleWebActivity.this, V6LoginActivity.class));

                    } else {
//                        Toast.makeText(V6ZhitouIndexActivity.this, jsonObject.optString("comment"), 2000).show();
                    }
                }

            }

            @Override
            public void onError() {
                // TODO Auto-generated method stub

            }
        };


        volleryUtil.setHeaders("token", getToken());
        volleryUtil.setRequestMethod(0);
        volleryUtil.execute(RuleWebActivity.this, Constant.URL + "/api/v5/user/accountCenter", "");
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (dialog != null) {
            dialog.dismiss();
        }
        BbtApplication.getInstance().removeActvity(this);

    }

    @Override
    protected void onPause() {
        super.onPause();

        if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) {
            v4_webview.onPause(); // 暂停网页中正在播放的视频  
        }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();

//        &token=

        String newtoken = getToken();
        try {
            newtoken = URLEncoder.encode(newtoken, "UTF-8");
//                        myurl1= URLEncoder.encode(myurl1, "UTF-8");
        } catch (UnsupportedEncodingException e) {
        }
        url=getIntent().getStringExtra("url");
//        v4_webview.loadUrl(Constant.URL + "api/v6/invest/ztbRules?app=true&token=" + newtoken);
        v4_webview.loadUrl(url);

    }

    @Override
    public void onBackPressed() {
        KShareViewActivityManager.getInstance(RuleWebActivity.this).finish(RuleWebActivity.this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if (v4_webview.canGoBack()) {
                v4_webview.goBack();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    WebChromeClient chromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {

            super.onProgressChanged(view, newProgress);
        }
    };

    private void initData() {

        v4_webview.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.e("myurl", url + "");

                return true;
            }

            @Override
            public void onReceivedSslError(WebView view,
                                           SslErrorHandler handler, SslError error) {
                // TODO Auto-generated method stub
//				super.onReceivedSslError(view, handler, error);
                handler.proceed();
            }

            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                // TODO Auto-generated method stub
                if (dialog != null & dialog.isShowing() == false) {
                    dialog.show();
                }
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                // TODO Auto-generated method stub
                if (dialog != null & dialog.isShowing() == true) {
                    dialog.dismiss();

                }
                super.onPageFinished(view, url);
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view,
                                                              String url) {
                // TODO Auto-generated method stub
                return super.shouldInterceptRequest(view, url);

            }
        });
        v4_webview.clearCache(true);

        v4_webview.setWebChromeClient(chromeClient);
//		GrowingIO.trackWebView(v4_webview, chromeClient);
        // 重新设置websettings WebSettings s = wb.getSettings();
        // s.setBuiltInZoomControls(true);
        // s.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        v4_webview.getSettings().setUseWideViewPort(true);

        v4_webview.getSettings().setLoadWithOverviewMode(true);
        v4_webview.getSettings().setSavePassword(true);
        v4_webview.getSettings().setSaveFormData(true);
        v4_webview.getSettings().setJavaScriptEnabled(true);
        // enable navigator.geolocation
        v4_webview.getSettings().setGeolocationEnabled(true);
        v4_webview.getSettings().setGeolocationDatabasePath(
                "/data/data/org.itri.html5webview/databases/");
        // enable Web Storage: localStorage, sessionStorage
//		v4_webview.getSettings().setDomStorageEnabled(true);
        v4_webview.requestFocus();
        v4_webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        // v4_webview.setScrollBarStyle(0);
        String ua = v4_webview.getSettings().getUserAgentString();
        v4_webview.getSettings().setUserAgentString(
                ua + "; " + "rmbbox_android");
        v4_webview.addJavascriptInterface(new JsInterfaces(RuleWebActivity.this),
                "AndroidWebView");
        v4_webview.getSettings().setBuiltInZoomControls(true);
        v4_webview.getSettings().setLayoutAlgorithm(
                WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        v4_webview.getSettings().setDomStorageEnabled(true);
        // Set cache size to 8 mb by default. should be more than enough
        v4_webview.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        // This next one is crazy. It's the DEFAULT location for your app's
        // cache
        // But it didn't work for me without this line.
        // UPDATE: no hardcoded path. Thanks to Kevin Hawkins
        String appCachePath = getApplicationContext().getCacheDir()
                .getAbsolutePath();
       /* if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            v4_webview.getSettings().setMixedContentMode(v4_webview.getSettings().MIXED_CONTENT_ALWAYS_ALLOW);
        }*/
        v4_webview.getSettings().setAllowFileAccess(true);
        v4_webview.getSettings().setAppCacheEnabled(true);
        v4_webview.getSettings().setJavaScriptEnabled(true);
        v4_webview.getSettings().setAppCachePath(appCachePath);
        v4_webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        v4_webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
//		v4_webview.getSettings().setSupportZoom(true);
        v4_webview.getSettings().setDefaultTextEncodingName("utf-8");

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_back:

            case R.id.img_back:
                finish();
                break;
        }


       /* RelativeLayout rl_back;
        ImageView img_back;*/
    }


    private class JsInterfaces {
        private Context mContext;


        public JsInterfaces(Context mContext) {
            super();
            this.mContext = mContext;

        }

        @JavascriptInterface
        public void finish(int type) {
            Log.e("finish", "finish");
            RuleWebActivity.this.finish();
        }


    }


    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 1) {

                share(RuleWebActivity.this, msg.getData().getString("description"), msg.getData().getString("title"), msg.getData().getString("sharelink"), msg.getData().getString("imageurl"));
            }


        }

        ;
    };


    private void initView() {


        v4_webview = (WebView) findViewById(R.id.v4_webview);
    }


    private void setImmersionStatus() {
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            // 透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // 透明导航栏
            //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }


}
